package com.home.fansea.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.home.fansea.entity.User;
import com.home.fansea.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @Projectname: MiniXYIot
 * @Filename: CaffeineConfig
 * @Author: FANSEA
 * @Data:2024/6/1 17:13
 */
@Configuration
@EnableCaching
@Slf4j
public class CaffeineConfig {
    @Autowired
    UserService userService;

    @Bean
    public CaffeineCacheManager caffeineCacheManager(){
        CaffeineCacheManager caffeine = new CaffeineCacheManager();
        caffeine.registerCustomCache("productDetails", Caffeine.newBuilder().recordStats()
                .maximumSize(1000).expireAfterWrite(5,TimeUnit.MINUTES)
                .build());
        caffeine.registerCustomCache("userDetails", Caffeine.newBuilder().recordStats()
                .maximumSize(1000).expireAfterWrite(5,TimeUnit.MINUTES)
                .build());
        /*使用refreshAfterWrite(long duration, TimeUnit unit)方法设置缓存项的刷新时间。这表示在缓存项过期之前，
        如果在此时间段内再次被访问，则会触发异步刷新。
        例如，refreshAfterWrite(4, TimeUnit.MINUTES)表示在缓存项写入后1分钟内，如果再次被访问，则会触发异步刷新。*/
        return caffeine;
    }

    @Bean
    public LoadingCache<Long, User> caffeine() {
        LoadingCache<Long, User> cache = Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build(this::loadUser);
        return cache;
    }

    private User loadUser(Long key) {
        // 加载缓存项的逻辑
        log.info("caffeine load user:{}", key);
        User user = userService.getById(key);
        return user;
    }

}
